<template>
  <div class="app-container">
    <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="demo-form-inline" v-hasPermi="['sa:examine:query']">
      <el-form-item label="月份" prop="examineDate">
        <el-date-picker
          v-model="queryParams.examineDate"
          type="month"
          value-format="yyyy-MM"
          :picker-options="pickerOptions"
          placeholder="选择月">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="用户" prop="examineName">
        <el-input v-model.trim="queryParams.examineName" size="small" :maxlength="15" placeholder="请输入用户"></el-input>
      </el-form-item>
      <el-form-item label="分数" prop="totalScore1">
        <el-input v-model.trim="queryParams.totalScore1" size="small" type="number" :min="0" placeholder="请输入最低总分"></el-input>
      </el-form-item>
      <el-form-item label="——" prop="totalScore2">
        <el-input v-model.trim="queryParams.totalScore2" size="small" type="number" :min="0" placeholder="请输入最高总分"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" v-hasPermi="['sa:examine:query']" @click="searchHandler">查询</el-button>
        <el-button icon="el-icon-refresh-right" size="mini" v-hasPermi="['sa:examine:query']" @click="resetForm('queryFormRef')">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="20">
      <el-col :span="12">
        <div class="grid-content bg-purple">
          <el-button icon="el-icon-share" type="primary" plain size="mini" v-hasPermi="['sa:examine:create']" @click="createHandler">生成</el-button>
<!--          <el-button plain type="primary" size="mini" icon="el-icon-plus" v-hasPermi="['sa:examine:add']" @click="openDialog(null)">增加</el-button>-->
          <el-button plain type="warning" size="mini" icon="el-icon-download" v-hasPermi="['sa:examine:export']" @click="exportHandler">导出</el-button>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="grid-content bg-purple"></div>
      </el-col>
    </el-row>

    <el-table
      ref="tableRef"
      :data="tableData"
      v-loading="loading"
      highlight-current-row
      max-height="680"
      v-horizontal-scroll="'auto'"
      style="width: 100%;margin-top: 10px;">
      <el-table-column
        type="index"
        label="序号"
        width="50"
        align="center"
      >
        <template slot-scope="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column
        property="examineDate"
        label="考核日期"
        align="center"
        width="100"
      />
      <el-table-column
        property="examineName"
        label="用户"
        align="center"
        width="80"
      />
      <el-table-column
        property="totalScore"
        label="总分"
        align="center"
        width="60"
      />
      <el-table-column
        property="collectScore"
        label="项目信息收集(<4:不合格 4:合格 6:良好 ≥8:优秀)"
        align="center"
      >
        <template slot="header" slot-scope="scope">
          <div>项目信息收集</div>
          <div>{{'<4:不合格'}}</div>
          <div>{{'4:合格'}}</div>
          <div>{{'6:良好'}}</div>
          <div>{{'≥8:优秀'}}</div>
        </template>
      </el-table-column>
      <el-table-column
        property="visitScore"
        label="客户拜访/邀约公司(<12:不合格 12:合格 20:良好 ≥25:优秀)"
        align="center"
      >
        <template slot="header" slot-scope="scope">
          <div>客户拜访/邀约公司</div>
          <div>{{'<12:不合格'}}</div>
          <div>{{'12:合格'}}</div>
          <div>{{'20:良好'}}</div>
          <div>{{'≥25:优秀'}}</div>
        </template>
      </el-table-column>
      <el-table-column
        property="merchandiserScore"
        label="销售跟单(<4:不合格 4:合格 6:良好 ≥8:优秀)"
        align="center"
      >
        <template slot="header" slot-scope="scope">
          <div>销售跟单</div>
          <div>{{'<4:不合格'}}</div>
          <div>{{'4:合格'}}</div>
          <div>{{'6:良好'}}</div>
          <div>{{'≥8:优秀'}}</div>
        </template>
      </el-table-column>
      <el-table-column
        property="changeScore"
        label="销售机会(1:不合格 2:合格 3:良好 4:优秀)"
        align="center"
      >
        <template slot="header" slot-scope="scope">
          <div>销售机会</div>
          <div>{{'1:不合格'}}</div>
          <div>{{'2:合格'}}</div>
          <div>{{'3:良好'}}</div>
          <div>{{'4:优秀'}}</div>
        </template>
      </el-table-column>
      <el-table-column
        property="weeklyScore"
        label="周报(4:合格)"
        align="center"
        width="80"
      >
        <template slot="header" slot-scope="scope">
          <div>周报</div>
          <div>4:合格</div>
        </template>
      </el-table-column>
      <el-table-column
        property="activityScore"
        label="服务大赛/展会活动(H*2)"
        align="center"
      >
        <template slot="header" slot-scope="scope">
          <div>服务大赛/展会活动</div>
          <div>H*2</div>
        </template>
      </el-table-column>
      <el-table-column
        property="tenderScore"
        label="商务标书制作及投标(X*2)"
        align="center"
      >
        <template slot="header" slot-scope="scope">
          <div>商务标书制作及投标</div>
          <div>X*2</div>
        </template>
      </el-table-column>
      <el-table-column
        property="businessScore"
        label="协助伙伴处理商务事宜(Z*2)"
        align="center"
      >
        <template slot="header" slot-scope="scope">
          <div>协助伙伴处理商务事宜</div>
          <div>Z*2</div>
        </template>
      </el-table-column>
      <el-table-column
        property="mediaScore"
        label="媒体宣传(M*1)"
        align="center"
        width="80"
      >
        <template slot="header" slot-scope="scope">
          <div>媒体宣传</div>
          <div>M*1</div>
        </template>
      </el-table-column>
      <el-table-column
        property="disciplineScore"
        label="纪律(J*2)"
        align="center"
        width="60"
      >
        <template slot="header" slot-scope="scope">
          <div>纪律</div>
          <div>J*2</div>
        </template>
      </el-table-column>
      <el-table-column
        property="remark"
        label="备注"
        align="center"
      />
      <el-table-column
        property="createTime"
        label="创建时间"
        align="center"
        sortable
        width="100"
      />
      <el-table-column
        label="操作"
        align="center"
        v-if="$auth.hasPermi('sa:examine:view') || $auth.hasPermi('sa:examine:edit')"
      >
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-view" v-hasPermi="['sa:examine:view']" @click="openViewDialog(scope.row)">查看</el-button>
          <el-button type="text" icon="el-icon-edit" v-hasPermi="['sa:examine:edit']" @click="openEditDialog(scope.row)">修改</el-button>
          <el-popconfirm
            confirm-button-text="是"
            cancel-button-text="否"
            title="确定删除吗？"
            @confirm="deleteHandler(scope.row)"
          >
            <el-button slot="reference" icon="el-icon-delete" type="text" v-hasPermi="['sa:examine:remove']" style="margin-left: 10px">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog
      :title="dialogTitle === 1 ? '增加' : '修改'"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
      :destroy-on-close="true"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" class="demo-form">
        <el-form-item label="客户名称" prop="name">
          <el-input v-model.trim="form.name" placeholder="请输入客户名称"></el-input>
        </el-form-item>
        <el-form-item label="省份" prop="province">
          <el-select v-model="form.province" filterable placeholder="请选择省份" style="width: 100%;">
            <el-option
              v-for="item in provinceList"
              :key="item.code"
              :label="item.name"
              :value="item.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所在地址" prop="address">
          <el-input v-model.trim="form.address" placeholder="请输入所在地址"></el-input>
        </el-form-item>
        <el-form-item label="客户属性" prop="isImportant">
          <el-select
            v-model="form.isImportant"
            filterable
            clearable
            placeholder="请选择客户属性" style="width: 100%;"
            @change="changePropertyHandler"
          >
            <el-option
              v-for="item in isImportantList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="重点依据" prop="basis" v-if="this.form.isImportant === 1">
          <el-select
            v-model="form.basis"
            filterable
            clearable
            placeholder="请选择重点依据"
            style="width: 100%;"
          >
            <el-option
              v-for="item in dict.type.sys_key_customer_basis"
              :key="+item.value"
              :label="item.label"
              :value="+item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model.trim="form.remark" type="textarea" :maxlength="200" placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('formRef')">提交</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="修改考核表"
      :visible.sync="tableEditShow"
      width="900px"
      close-on-click-modal
      :destroy-on-close="true"
    >
      <ExamineEditInfo :info="editInfo" @get-date="getList"/>
    </el-dialog>

    <el-dialog
      title="查看考核表"
      :visible.sync="tableViewShow"
      width="900px"
      close-on-click-modal
      :destroy-on-close="true"
    >
      <ExamineInfo :info="viewInfo"/>
    </el-dialog>

  </div>
</template>
<script>
import {addDataApi, deleteDataApi, getDataListApi, updateDataApi, createDataApi} from "@/api/crm/sa/examine";
import ProvinceData from '@/views/crm/data/province.json'
import {getUserProfile} from "@/api/system/user";
import ExamineInfo from "./info.vue";
import ExamineEditInfo from "./editInfo.vue";
// import {isNumberStr} from "@/utils";

export default {
  name: 'ExamineView',
  components: {
    ExamineInfo,
    ExamineEditInfo
  },
  dicts: ['sys_key_customer_basis'],
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          const date = new Date() // 当前日期（具体到秒）
          const year = date.getFullYear() // 当前年份
          let month = date.getMonth() + 1 // 当前月份
          if (month >= 1 && month <= 9) {  // 1-9月份前加0
            month = '0' + month
          }
          const currentdate = year.toString() + month.toString()
          const timeyear = time.getFullYear()
          let timemonth = time.getMonth() + 1
          if (timemonth >= 1 && timemonth <= 9) {
            timemonth = '0' + timemonth
          }
          const timedate = timeyear.toString() + timemonth.toString()
          // console.log('timedate--', timedate, 'currentdate--', currentdate);
          /**当月 */
          // return timedate < currentdate || currentdate < timedate
          /** 当月及以后的月份 */
          // return timedate < currentdate
          /** 当月及以前的月份 */
          return timedate > currentdate - 1
        }
      },
      // 显示考核表的用户信息
      viewInfo: {},
      editInfo: {},
      // 查看考核表
      tableViewShow: false,
      // 修改考核表
      tableEditShow: false,
      // 加载动画
      loading: true,
      // 省份数据
      provinceList: [],
      // 弹框标题 1是增加 其他是修改
      dialogTitle: 1,
      // 弹框显示
      dialogVisible: false,
      // 新增和修改参数
      form: {
        activityScore: 0, // 活动和大赛的分数
        businessScore: 0, // 协助伙伴分数
        changeScore: 0, // 新增销售机会分数
        collectScore: 0, // 项目收集分数
        createBy: "", // 用户
        createTime: "", // 创建时间
        disciplineScore: 0, // 纪律分数
        examineDate: "", // 考核日期
        examineName: "", // 考核人
        id: null,
        mediaScore: 0, // 媒体宣传分数
        merchandiserScore: 0, // 销售跟单分数
        remark: "", // 备注
        tenderScore: 0, // 标书分数
        totalScore: 0, // 总分
        updateBy: "", // 更新人
        updateTime: "", // 更新时间
        visitScore: 0, // 拜访记录分数
        weeklyScore: 0, // 周报分数
      },
      // 重点客户下拉数据
      isImportantList: [
        {
          value: 0,
          label: '普通客户'
        },
        {
          value: 1,
          label: '重点客户'
        }
      ],
      // 表单的校验规则
      rules: {
        name: [
          { required: true, message: '请填写客户名称', trigger: 'blur' }
        ],
        isImportant: [
          { required: true, message: '请选择客户属性', trigger: 'change' }
        ],
        province: [
          { required: true, message: '请选择省份', trigger: 'change' }
        ],
      },
      // 表格数据
      tableData: [],
      // 总数条数
      total: 0,
      // 查询参数
      queryParams: {
        examineDate: "",
        totalScore1: "", // 是否重点客户 0是普通 1是重点 *
        totalScore2: "", // 学校名 *
        pageNum: 1,
        pageSize: 10,
      },
      // 用户信息
      user: {},
      roleGroup: {},
      postGroup: {},
    }
  },
  watch: {
    'form.isImportant': {
      handler(newV) {
        if(newV !== 1) {
          this.form.basis = null
        }
      }
    },
  },
  created() {
    this.provinceList = ProvinceData
    this.getList()
    this.getUserinfo()
  },
  activated() {
    this.getList()
  },
  methods: {
    // 生成的回调
    async createHandler() {
      if(!this.queryParams.examineDate) {
        this.$notify.warning('请选择月份', '警告')
        return false
      }
      const res = await createDataApi({
        ...this.queryParams,
        createBy: this.user.nickName,
        updateBy: this.user.nickName,
        userId: this.user.userId,
      })
      if(res.code === 200){
        await this.getList()
      }
    },
    // 打开修改的弹窗
    openEditDialog(row) {
      this.editInfo = { ...row }
      this.tableEditShow = true
    },
    openViewDialog(row) {
      this.viewInfo = { ...row }
      this.tableViewShow = true
    },
    toPath(row) {
      this.$router.push({ name: 'CRMExamineInfo', query: { id: row.id } })
    },
    // 选择重点的回调
    changePropertyHandler(val) {
      if(val === 0) {
        this.form.basis = null
      }
    },
    // 获取根据list中的value返回label
    getListValue(data, list, value = 'value') {
      let label = ''
      list.map((item) => {
        if(+item[value] === +data) {
          label = item.label
        }
      })
      return label
    },
    // 获取用户信息
    getUserinfo() {
      getUserProfile().then(response => {
        this.user = response.data;
        this.roleGroup = response.roleGroup;
        this.postGroup = response.postGroup;
      });
    },
    // 获取数据
    async getList() {
      this.loading = true
      const res = await getDataListApi(this.queryParams)
      if(res.code === 200) {
        this.tableData = res.rows
        this.total = res.total
      }
      this.loading = false
    },
    // 搜索的回调
    searchHandler() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 删除的回调
    async deleteHandler(row) {
      const res = await deleteDataApi({
        id: row.id
      })
      if(res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 打开弹窗
    openDialog(row) {
      if (row) {
        this.form = {...row}
        this.dialogTitle = 2
      } else {
        this.form = { ...this.$options.data().form }
        this.dialogTitle = 1
      }
      this.dialogVisible = true
      this.resetForm('formRef')
    },
    // 导出的回调
    async exportHandler() {
      this.download('crm/kpi/export', {
        ...this.queryParams,
        userId: this.user.userId,
        deptId: this.user.deptId,
      }, `kpi_${new Date().getTime()}.xlsx`)
    },
    // 表单提交
    submitForm(formName) {
      if(this.form.isImportant === 1 && !(this.form.basis)) {
        this.$notify({
          title: '警告',
          message: '请选择重点依据',
          type: 'warning'
        });
        return false
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(this.dialogTitle === 1) {
            this.addDataHandler()
          } else {
            this.updateDataHandler()
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 增加数据的回调
    async addDataHandler() {
      const payload = {
        ...this.form,
        createBy: this.user.nickName,
        updateBy: this.user.nickName,
        userId: this.user.userId,
      }
      const res = await addDataApi(payload)
      if(res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 修改数据的回调
    async updateDataHandler() {
      const payload = {
        ...this.form,
        updateBy: this.user.nickName,
      }
      const res = await updateDataApi(payload)
      if(res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 重置表单
    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
    }
  },
}
</script>
<style scoped lang="scss">

</style>
